package com.corner.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.corner.R;
import com.corner.app.App;
import com.corner.app.ConsTants;
import com.corner.app.GlobalParams;
import com.corner.model.cornerservice.domain.Info;

import com.corner.model.db.DBConstans;
import com.corner.model.db.Session;
import com.corner.model.leancloud.helper.MessageHelperV2;
import com.corner.presenter.imp.ChatPresenter;
import com.corner.ui.adapter.ChatMessageAdapter;
import com.corner.ui.base.BaseActivity;
import com.corner.ui.view.IChatView;
import com.corner.utils.AppManager;
import com.corner.utils.BitmapUtil;
import com.corner.utils.CommonUtil;
import com.corner.utils.DialogUtil;
import com.corner.utils.IntentUtil;
import com.corner.utils.NotificationUtil;
import com.corner.utils.SoftInputUtil;
import com.corner.utils.ToastUtil;
import com.corner.utils.view.AudioHelper;
import com.corner.utils.view.BaseRecordNoticeCallback;
import com.corner.utils.view.CustomFont;
import com.corner.utils.view.FindView;
import com.corner.utils.view.InputBox;
import com.corner.utils.view.MainActionBar;
import com.corner.utils.view.widget.XListView;
import com.facebook.drawee.view.SimpleDraweeView;

import java.io.File;
import java.io.IOException;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

/**
 * Created by Administrator on 2015/5/7.
 */
public class ChatActivity extends BaseActivity<ChatPresenter> implements View.OnClickListener, IChatView, View.OnTouchListener {

    public static final String INTENT_ID = "INTENT_ID";
    public static final int COMMENT = 1;
    public static final int CHAT = 2;
    public static final int SHARE = 3;

    public static final String USER_ID_IN_LONG = "userId";
    public static final String INFO_PRAC = "infoPrac";
    public static final String LOCATION_ID = "LOCATION_ID";
    public static final String LOCATION_NAME = "LOCATION_NAME";
    public static final String NICK_NAME = "NICK_NAME";

    public static final int PICTURE = 0;
    public static final int CAMERA = 1;
    public static final int PICVOICE = 2;
    public static final int RECORD_AUDIO_FOR_PIC = 4;
    public static final int PREVIEW_PIC = 5;
    public static String userId;
    private MainActionBar actionBar;
    @FindView(R.id.view_chat_input_box)
    private InputBox inputBox;
    @FindView(R.id.lv_chat_message_list)
    private XListView lvMessage;
    @FindView(R.id.iv_chat_conment_preview_pic)
    private SimpleDraweeView ivPrePic;
    @FindView(R.id.ll_chat_conment_preview)
    private LinearLayout llPreComment;
    @CustomFont(ConsTants.TYPE_FACE)
    @FindView(R.id.tv_chat_conment_preview_text)
    private TextView tvPreTxt;
    @FindView(R.id.iv_chat_conment_preview_remove)
    private ImageView ivPreRemove;
    private int currRequestCode;
    private String cameraPicPath;
    private ChatMessageAdapter adapter;
    private String currPicPath;
    /**
     * 是否评论被移除
     */
    private boolean isRemoved = false;
    private Dialog resendOrDeleteDialog;
    private TextView tvResend;
    private TextView tvDelete;
    private Dialog copyOrDeleteDialog;
    private TextView tvCopy;
    private TextView tvAddBlackList;
    private Dialog moretDialog;
    private TextView tvReport;
    private Dialog addBlackListDialog;
    private TextView tvAddBlackListCancel;
    private TextView tvAddBlackListEnsure;
    private TextView tvReportCancel;
    private TextView tvReortEnsure;
    private Dialog reportDialog;
    private int intentId;
    private String locationId;
    private Info info;


    @Override
    protected ChatPresenter createP() {
        return new ChatPresenter();
    }

    @Override
    protected void setOnClick() {
        inputBox.tvSend.setOnClickListener(this);
        inputBox.tvImgVoc.setOnClickListener(this);
        inputBox.tvCamera.setOnClickListener(this);
        inputBox.tvPic.setOnClickListener(this);
        ivPreRemove.setOnClickListener(this);
        actionBar.btnLeft.setOnClickListener(this);
        actionBar.ivRight.setOnClickListener(this);
        lvMessage.setPullLoadEnable(false);
        lvMessage.setOnTouchListener(this);
        lvMessage.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                presenter.loadMoreSessions();
            }

            @Override
            public void onLoadMore() {
            }
        });
    }

    public void hideSoftInput() {
        SoftInputUtil.hideSoftInput(ChatActivity.this, inputBox.etChatInfo);
        inputBox.llImgVocHide.setVisibility(View.GONE);
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        final Intent intent = getIntent();
        NotificationUtil.cancleNotify(App.application, ConsTants.MESSAGE_NOTIFY);
        intentId = intent.getIntExtra(INTENT_ID, CHAT);
        if (intentId == COMMENT) {
            llPreComment.setVisibility(View.VISIBLE);

            info = intent.getParcelableExtra(INFO_PRAC);
            switch (info.getType()) {
                case Info.A:
                    tvPreTxt.setText(getString(R.string.chat_comment_audio));
                    break;
                case Info.T:
                    tvPreTxt.setText(info.getText());
                    break;
                case Info.TP:
                    tvPreTxt.setText(info.getText());
                    ivPrePic.setVisibility(View.VISIBLE);
                    if (info.getImageUrl() != null)
                        ivPrePic.setImageURI(Uri.parse(info.getImageUrl()));
                    break;
                case Info.P:
                    ivPrePic.setVisibility(View.VISIBLE);
                    if (info.getImageUrl() != null)
                        ivPrePic.setImageURI(Uri.parse(info.getImageUrl()));
                    break;
                case Info.AP:
                    tvPreTxt.setText(getString(R.string.chat_comment_pic_audio));
                    ivPrePic.setVisibility(View.VISIBLE);
                    if (info.getImageUrl() != null)
                        ivPrePic.setImageURI(Uri.parse(info.getImageUrl()));
                    break;
            }
            showEditTextAndOpenSoftInput();
        } else if (intentId == SHARE) {
            String locationName = intent.getStringExtra(LOCATION_NAME);
            locationId = intent.getStringExtra(LOCATION_ID);
            llPreComment.setVisibility(View.VISIBLE);
            tvPreTxt.setText(locationName);
            showEditTextAndOpenSoftInput();
        } else {
            isRemoved = true;
        }
        userId = String.valueOf(intent.getLongExtra(USER_ID_IN_LONG,0));
        String nickname = intent.getStringExtra(NICK_NAME);
        if (!TextUtils.isEmpty(nickname)){
            actionBar.tvMiddle.setText(nickname);
        }
        presenter.requestSessions(userId);
    }

    /**
     * 展示输入框
     */
    private void showEditText() {
        inputBox.initWigt();
        inputBox.etChatInfo.setVisibility(View.VISIBLE);
//        inputBox.ibAddVoice.setVisibility(View.VISIBLE);
        inputBox.tvAddVoice.setVisibility(View.VISIBLE);
    }

    /**
     * 展示输入框并打开输入法
     */
    private void showEditTextWithoutOpenSoftInput() {
        showEditText();
        SoftInputUtil.hideSoftInput(this, inputBox.etChatInfo);
    }

    /**
     * 展示输入框，不打开输入法
     */
    private void showEditTextAndOpenSoftInput() {
        showEditText();
        SoftInputUtil.openSoftInput(this, inputBox.etChatInfo);
    }
    @Override
    public void initView() {
        super.initView();
        actionBar = new MainActionBar(this);
        inputBox.setActivity(this);
        initAudioBtn();
        showEditTextWithoutOpenSoftInput();
        actionBar.initActionBarButton();
        actionBar.btnLeft.setVisibility(View.VISIBLE);
//        actionBar.btnLeft.setText(R.string.go_back);
        actionBar.ivRight.setVisibility(View.VISIBLE);
        actionBar.ivRight.setImageResource(R.drawable.action_bar_more);
        actionBar.ivRight.setPadding(actionBar.ivRight.getPaddingLeft(), actionBar.ivRight.getPaddingTop(), actionBar.ivRight.getPaddingRight() / 4, actionBar.ivRight.getPaddingBottom());
//        actionBar.tvMiddle.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);//下划线
        actionBar.tvMiddle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.location_list_item_name_szie));
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_chat);
    }

    @Override
    public void onClick(View v) {
        if (v == inputBox.tvSend) {
            if (isRemoved) {
                MessageHelperV2.sendText(inputBox.etChatInfo.getText().toString(), userId);
                comeToBottom();
            } else {
                if (intentId == COMMENT) {
                    MessageHelperV2.sendComment(inputBox.etChatInfo.getText().toString(), info.getObjectId(), userId);
                    comeToBottom();
                    isRemoved = true;
                    ivPreRemove.performClick();
                } else if (intentId == SHARE) {
                    MessageHelperV2.sendShare(inputBox.etChatInfo.getText().toString(), Long.valueOf(locationId), userId);
                    comeToBottom();
                    isRemoved = true;
                    ivPreRemove.performClick();
                }
            }
            clearInputBox();
        } else if (v == inputBox.tvImgVoc || v == inputBox.tvPic) {
            // 拿照片
            Intent intent_file = IntentUtil.getPicIntent();
            if (v == inputBox.tvImgVoc) {
                this.currRequestCode = PICVOICE;
            } else {
                this.currRequestCode = PICTURE;
            }
            startActivityForResult(intent_file, currRequestCode);
        } else if (v == inputBox.tvCamera) {
            // 照相
            Intent intent_camera;
            try {
                cameraPicPath = GlobalParams.APPFIEPATH + "/camera/"
                        + System.currentTimeMillis() + ".jpg";
                intent_camera = IntentUtil.getCameraIntent(cameraPicPath);
                this.currRequestCode = CAMERA;
                startActivityForResult(intent_camera, this.currRequestCode);
            } catch (IOException e) {
                CommonUtil.showSDcardError(getApplicationContext());
                e.printStackTrace();
            }
        } else {
            switch (v.getId()) {
                case R.id.iv_chat_conment_preview_remove:
                    isRemoved = true;
                    llPreComment.setVisibility(View.GONE);
                    inputBox.tvSend.setVisibility(View.GONE);
//                    inputBox.ibAddVoice.setVisibility(View.VISIBLE);
                    inputBox.tvAddVoice.setVisibility(View.VISIBLE);
                    break;
                case R.id.tv_chat_dialog_resend:
                    resend((Session) v.getTag());
                    DialogUtil.hideDialog(resendOrDeleteDialog);
                    break;
                case R.id.tv_chat_dialog_delete:
                    delete((Session) v.getTag());
                    if (resendOrDeleteDialog != null)
                        DialogUtil.hideDialog(resendOrDeleteDialog);
                    if (copyOrDeleteDialog != null)
                        DialogUtil.hideDialog(copyOrDeleteDialog);
                    break;
                case R.id.tv_chat_dialog_copy:
                    copy((Session) v.getTag());
                    DialogUtil.hideDialog(copyOrDeleteDialog);
                    break;
                case R.id.btn_actionbar_left:
                    SoftInputUtil.hideSoftInput(this, inputBox.etChatInfo);
                    AppManager.getInstance().finishActivity(this);
                    break;
                case R.id.iv_actionbar_right:
                    showMoreDialog();
                    break;
                case R.id.tv_chat_dialog_add_to_blacklist:
                    showAddBlackDialog();
                    DialogUtil.hideDialog(moretDialog);
                    break;
                case R.id.tv_chat_dialog_add_to_blacklist_ensure:
                    presenter.addToBlackList(userId);
                    DialogUtil.hideDialog(addBlackListDialog);
                    break;
                case R.id.tv_chat_dialog_add_to_blacklist_cancel:
                    DialogUtil.hideDialog(addBlackListDialog);
                    break;
                case R.id.tv_chat_dialog_report:
                    showRePort();
                    DialogUtil.hideDialog(moretDialog);
                    break;
                case R.id.tv_info_item_dialog_report_ensure:
                    presenter.report(userId);
                    DialogUtil.hideDialog(reportDialog);
                    break;
                case R.id.tv_info_item_dialog_report_cancel:
                    DialogUtil.hideDialog(reportDialog);
                    break;
            }
        }
    }

    public void showRePort() {
        if (reportDialog == null) {
            //自己发的内容
            reportDialog = DialogUtil.showDiaLog(R.layout.dialog_report_info, this);
            tvReortEnsure = (TextView) reportDialog.findViewById(R.id.tv_info_item_dialog_report_ensure);
            tvReportCancel = (TextView) reportDialog.findViewById(R.id.tv_info_item_dialog_report_cancel);
            tvReortEnsure.setOnClickListener(this);
            tvReportCancel.setOnClickListener(this);
        } else {
            reportDialog.show();
        }
    }


    private void showAddBlackDialog() {
        if (addBlackListDialog == null) {
            //自己发的内容
            addBlackListDialog = DialogUtil.showDiaLog(R.layout.dialog_add_to_blacklist, this);
            tvAddBlackListEnsure = (TextView) addBlackListDialog.findViewById(R.id.tv_chat_dialog_add_to_blacklist_ensure);
            tvAddBlackListCancel = (TextView) addBlackListDialog.findViewById(R.id.tv_chat_dialog_add_to_blacklist_cancel);
            tvAddBlackListEnsure.setOnClickListener(this);
            tvAddBlackListCancel.setOnClickListener(this);
        } else {
            addBlackListDialog.show();
        }
    }

    private void showMoreDialog() {
        if (moretDialog == null) {
            //自己发的内容
            moretDialog = DialogUtil.showDiaLog(R.layout.dialog_contact_black_or_report, this);
            tvAddBlackList = (TextView) moretDialog.findViewById(R.id.tv_chat_dialog_add_to_blacklist);
            tvReport = (TextView) moretDialog.findViewById(R.id.tv_chat_dialog_report);
            tvAddBlackList.setOnClickListener(this);
            tvReport.setOnClickListener(this);
        } else {
            moretDialog.show();
        }
    }

    /**
     * 复制到剪切板
     *
     * @param session
     */
    private void copy(Session session) {
        CommonUtil.copyTextToClipBoard(this, session.getText());
        ToastUtil.showCustomToastInRelease(this, getString(R.string.chat_copy_to_clip_board));
    }


    /**
     * 删除
     *
     * @param session
     */
    private void delete(Session session) {
        App.application.daoSession.getSessionDao().delete(session);
    }

    /**
     * 重发
     *
     * @param session
     */
    private void resend(Session session) {
        MessageHelperV2.resend(session);
    }

    /**
     * 初始化录音按键
     */
    private void initAudioBtn() {
        AudioHelper audioHelper = new AudioHelper(inputBox.btnPressAudio,
                new AudioHelper.OnFinishRecordCallback() {

                    @Override
                    public void finish(boolean isOk, String path) {
                        if (isOk) {
                            MessageHelperV2.sendAudio(path,
                                    userId);
                        }
                    }
                });
        audioHelper.setRecoderNoticeCallback(new BaseRecordNoticeCallback(
                inputBox, getApplicationContext()) {
            @Override
            protected void show(PopupWindow popWindow, View parent) {
                popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PREVIEW_PIC) {  //预览图片的返回
            if (data != null) {
                boolean isSend = data.getBooleanExtra(PreviewPicActivity.IS_SEND, false);
                if (isSend) {
                    //发送图片，已经压缩过了，不必再压缩
                    MessageHelperV2.sendPic(currPicPath, userId);
                    comeToBottom();
                    inputBox.llImgVocHide.setVisibility(View.GONE);
                } else {
                    startActivityForResult(IntentUtil.getPicIntent(),
                            currRequestCode);
                }
            }
        } else if (requestCode == RECORD_AUDIO_FOR_PIC) { //为图片录音的返回
            if (resultCode == Record4Pic.RESULT_OK) {
                String audioPath = data.getStringExtra(Record4Pic.AUDIO_PATH);
                //没有压缩过，压缩发送
                compressPicAndSend(currPicPath, audioPath);
                inputBox.llImgVocHide.setVisibility(View.GONE);
                currPicPath = null;
            } else if (resultCode == Record4Pic.RESULT_CANCEL) {
                currPicPath = null;
            } else if (resultCode == Record4Pic.RESULT_RESELECT) {
                currPicPath = null;
                startActivityForResult(IntentUtil.getPicIntent(),
                        currRequestCode);
            }
        } else { //相册、拍照的返回
            String picturePath = null;
            if (requestCode == PICTURE || requestCode == PICVOICE) { //相册
                if (data == null)
                    return;
                picturePath = getPicturePathInIntent(data);
            } else if ((requestCode == CAMERA)
                    && (resultCode == Activity.RESULT_OK)) { //拍照
                picturePath = cameraPicPath;
            }
            if (picturePath != null) {
                if (requestCode == PICVOICE) {
                    //去为图片录音
                    data.setClass(getApplicationContext(), Record4Pic.class);
                    data.putExtra(Record4Pic.PICTUREPATH,
                            picturePath);
                    startActivityForResult(data, RECORD_AUDIO_FOR_PIC);
                    currPicPath = picturePath;
                } else if (requestCode == PICTURE) {
                    //去为预览图片
                    try {
                        String path = GlobalParams.APPFIEPATH + "/pic/" + new File(picturePath).getName();
                        BitmapUtil.compressBitmap(picturePath, path);
                        Intent intent = new Intent(this, PreviewPicActivity.class);
                        intent.putExtra(PreviewPicActivity.PIC_PATH, path);
                        startActivityForResult(intent, PREVIEW_PIC);
                        currPicPath = path;
                    } catch (IOException e) {
                        e.printStackTrace();
                        showError(getString(R.string.chat_compress_pic_error));
                    }
                } else {
                    //拍照成功，直接压缩发送图片
                    compressPicAndSend(picturePath, null);
                    inputBox.llImgVocHide.setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * 获取intent中的图片路径
     *
     * @param data
     * @return
     */
    private String getPicturePathInIntent(Intent data) {
        String picturePath;
        Uri selectedImage = data.getData();
        String[] filePathColumns = {MediaStore.Images.Media.DATA};
        Cursor c = this.getContentResolver().query(selectedImage,
                filePathColumns, null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePathColumns[0]);
        picturePath = c.getString(columnIndex);
        c.close();
        return picturePath;
    }

    /**
     * 压缩图片并发送
     *
     * @param picPath
     * @param audioPath
     */
    private void compressPicAndSend(final String picPath, final String audioPath) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                String path = GlobalParams.APPFIEPATH + "/pic/" + picPath.hashCode();
                try {
                    BitmapUtil.compressBitmap(picPath, path);
                    subscriber.onNext(path);
                } catch (IOException e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        }).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (audioPath == null) {
                    MessageHelperV2.sendPic(s, userId);
                    comeToBottom();
                } else {
                    MessageHelperV2.sendPicAudio(s, audioPath, userId);
                    comeToBottom();
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                showError(getString(R.string.chat_compress_pic_error)+ throwable.getMessage());
            }
        });
    }

    /**
     * 清空输入框
     */

    private void clearInputBox() {
        inputBox.clearInputBox();
    }


    /**
     * 显示重发和删除的对话框
     *
     * @param session
     */
    public void showReSentDialog(Session session) {
        if (resendOrDeleteDialog == null) {
            resendOrDeleteDialog = DialogUtil.showDiaLog(R.layout.dialog_message_resent_or_delete, this);
            tvResend = (TextView) resendOrDeleteDialog.findViewById(R.id.tv_chat_dialog_resend);
            tvDelete = (TextView) resendOrDeleteDialog.findViewById(R.id.tv_chat_dialog_delete);
            tvResend.setOnClickListener(this);
            tvDelete.setOnClickListener(this);
        } else {
            resendOrDeleteDialog.show();
        }
        tvResend.setTag(session);
        tvDelete.setTag(session);
    }


    @Override
    public void showSessions(List<Session> sessions, String selfAvaterUrl, String friendAvaterUrl,String nickName) {
        adapter = new ChatMessageAdapter(ChatActivity.this, sessions, selfAvaterUrl, friendAvaterUrl);
        if (TextUtils.isEmpty(actionBar.tvMiddle.getText())){
            actionBar.tvMiddle.setText(nickName);
        }
        lvMessage.setAdapter(adapter);
    }

    @Override
    public void showLoadMoreSessions(List<Session> sessions) {
        int lastItemCount = adapter.getCount();
        adapter.changeList(sessions);
        lvMessage.setSelection(sessions.size() - lastItemCount);
    }

    @Override
    public void showUpdateSessions(List<Session> sessions) {
        if (adapter != null)
            adapter.changeList(sessions);
        else {
            presenter.requestSessions(userId);
        }
    }

    @Override
    public void comeToBottom() {
        if (adapter != null)
            lvMessage.setSelection(adapter.getCount());
    }

    @Override
    public void loadComplete() {
        lvMessage.stopRefresh();
    }

    @Override
    public void addBlackListSucess() {
        ToastUtil.showCustomToastInRelease(App.application, getString(R.string.add_to_blacklist_sucess));
        AppManager.getInstance().finishActivity(this);
    }

    @Override
    public void showReportSucess() {
        ToastUtil.showCustomToastInRelease(App.application, getString(R.string.info_report_sucess));
    }

    @Override
    public void showReportError(String message) {
        ToastUtil.showCustomToastInRelease(App.application, message);
    }

    @Override
    public void showError(String message) {
        ToastUtil.showCustomToastInRelease(App.application, message);
    }

    /**
     * 显示复制与删除对话框
     *
     * @param session
     */
    public void showCopyOrDeleteDialog(Session session) {
        if (copyOrDeleteDialog == null) {
            copyOrDeleteDialog = DialogUtil.showDiaLog(R.layout.dialog_message_copy_or_delete, this);
            tvCopy = (TextView) copyOrDeleteDialog.findViewById(R.id.tv_chat_dialog_copy);
            tvDelete = (TextView) copyOrDeleteDialog.findViewById(R.id.tv_chat_dialog_delete);
            tvCopy.setOnClickListener(this);
            tvDelete.setOnClickListener(this);
        } else {
            copyOrDeleteDialog.show();
        }
        switch (session.getType()) {
            case DBConstans.AUDIO:
            case DBConstans.PIC:
            case DBConstans.PIC_AUDIO:
                tvCopy.setVisibility(View.GONE);
                break;
            case DBConstans.TEXT:
            case DBConstans.COMMENT:
                tvCopy.setVisibility(View.VISIBLE);
                break;
        }
        tvCopy.setTag(session);
        tvDelete.setTag(session);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (adapter != null) {
            adapter.onDestroy();
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        hideSoftInput();
        return false;
    }
}
